package cn.dlc.com.order.controller;

import cn.dlc.com.common.entity.Order;
import cn.dlc.com.order.service.OrderService;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

/**
 * @author 邓立川
 * @date 2021/1/10 10:41
 * @desc 测试消息的发送
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @PostMapping
    public Order sendOrder(){
        Order order = new Order();
        order.setId(1L);
        order.setOrderName("排骨饭");
        order.setCreateTime(new Date());

        System.out.println("模拟下单成功.....: " + order.getOrderName());
        // 发送消息
        rocketMQTemplate.convertAndSend("order-topic", JSON.toJSONString(order));
        return order;
    }


    /**
     * 发送同步消息
     * @return
     */
    @GetMapping("sync")
    public Order sendSyncMsg(){
        // 发送消息
        rocketMQTemplate.syncSend("order-topic:tag", "同步消息",5000);
        return new Order();
    }

    @GetMapping("async")
    public void sendAsyncMsg(){
        rocketMQTemplate.asyncSend("order-topic:tag", "异步消息", new SendCallback() {
            // 监听消息是否成功
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            // 消息发送异常的回调
            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable);
            }
        });
    }

    @GetMapping("oneway")
    public void sendOneWay(){
        rocketMQTemplate.sendOneWay("order-topic:tag","单向消息");
    }

    @GetMapping("orderly/oneway")
    public void sendOneWayOrderly(){
        // 发送10条消息
        for (int i = 0; i < 10 ; i++) {
            rocketMQTemplate.sendOneWayOrderly("order-topic:tag","单向消息","xx");
        }
    }

    /**
     * 下单方法，不用在意命名是否规范，主要是为了方便测试
     * @param orderName
     * @return
     */
    @GetMapping("{orderName}")
    public Order createOrder(@PathVariable("orderName") String orderName){
        Order order = new Order();
        order.setOrderName(orderName);
        orderService.createOrder(order);

        return order;
    }
}
